//
//  UploadPhotoViewController.swift
//  IDF
//
//  Created by 陈徐挺 on 30/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import ALCameraViewController
import AliyunOSSiOS
import Kingfisher
import PromiseKit
import Proposer
import SVProgressHUD
import Photos

class UploadPhotoViewController: BaseViewController {

    var userCard: UserCard!
    @IBOutlet weak var saveButtonView: FooterButtonView!

    @IBOutlet weak var IDCardBtn: UIButton!
    @IBOutlet weak var workingIDCardBtn: UIButton!
    @IBOutlet weak var delIDCardBtn: UIButton!
    @IBOutlet weak var delWorkinglIDCardBtn: UIButton!
    @IBOutlet weak var delIDCardImage: UIButton!
    @IBOutlet weak var delWorkinglIDCardImage: UIButton!

    var libraryEnabled: Bool = true
    var croppingEnabled: Bool = false
    var allowResizing: Bool = true
    var allowMoving: Bool = false
    var minimumSize: CGSize = CGSize(width: kWidth - 30 - 30, height: (kWidth - 30 - 30) * 5 / 9)

    var croppingParameters: CroppingParameters {
        return CroppingParameters(isEnabled: croppingEnabled, allowResizing: allowResizing, allowMoving: allowMoving, minimumSize: minimumSize)
    }
    @IBOutlet weak var workingIDCardImageView: UIImageView!

    @IBOutlet weak var IDCardImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        navigationItem.title = "Upload photo"
        if userCard.idCardUrl == "" {
            IDCardImageView.isHidden = true
            delIDCardBtn.isHidden = true
            delIDCardImage.isHidden = true
        } else {
            IDCardBtn.isEnabled = false
            let url = URL(string: userCard.idCardUrl)
            IDCardImageView.kf.setImage(with: url, options: [.forceRefresh])
        }
        if userCard.workinfoCardUrl == "" {
            workingIDCardImageView.isHidden = true
            delWorkinglIDCardBtn.isHidden = true
            delWorkinglIDCardImage.isHidden = true
        } else {
            workingIDCardBtn.isEnabled = false
            let url = URL(string: userCard.workinfoCardUrl)
            workingIDCardImageView.kf.setImage(with: url, options: [.forceRefresh])
        }
        saveButtonView.doneButton.setBlockFor(.touchUpInside) { [weak self] (button) in
            EZAlertController.alert("Save information", message: "Whether to save the modified information？", buttons: ["Give up", "Save"], tapBlock: { (_, index) in
                if index == 1 {
                    SVProgressHUD.show()
                    let _ = self?.saveImage().then { _ -> Void in
                        let _ = self?.userCard.save().then { _ -> Void in
                            nowNavgationController.popViewController(animated: true)
                        }
                    }
                }
            })

        }
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    @IBAction func delImage(_ sender: UIButton) {
        if sender.tag == 1 {
            IDCardImageView.isHidden = true
            IDCardBtn.isEnabled = true
            delIDCardBtn.isHidden = true
            delIDCardImage.isHidden = true
            userCard.idCardUrl = ""

        } else {
            workingIDCardImageView.isHidden = true
            workingIDCardBtn.isEnabled = true
            delWorkinglIDCardBtn.isHidden = true
            delWorkinglIDCardImage.isHidden = true
            userCard.workinfoCardUrl = ""
        }
    }


    @IBAction func uploadIDCard(_ sender: UIButton) {

        let cameraViewController = CameraViewController(croppingParameters: self.croppingParameters, allowsLibraryAccess: false, allowsSwapCameraOrientation: true, allowVolumeButtonCapture: true) { [weak self] image, asset in
            if let img = image {
                self?.IDCardImageView.image = img.byRotateLeft90()
                self?.IDCardImageView.isHidden = false
                self?.IDCardBtn.isEnabled = false
                self?.delIDCardBtn.isHidden = false
                self?.delIDCardImage.isHidden = false
            }
            self?.dismiss(animated: true, completion: nil)
        }
        present(cameraViewController, animated: true, completion: nil)
    }



    @IBAction func uploadWorkingIDCard(_ sender: UIButton) {
        let cameraViewController = CameraViewController(croppingParameters: croppingParameters, allowsLibraryAccess: false, allowsSwapCameraOrientation: true, allowVolumeButtonCapture: true) { [weak self] image, asset in
            if let img = image {
                self?.workingIDCardImageView.image = img.byRotateLeft90()
                self?.workingIDCardImageView.isHidden = false
                self?.workingIDCardBtn.isEnabled = false
                self?.delWorkinglIDCardBtn.isHidden = false
                self?.delWorkinglIDCardImage.isHidden = false
            }
            self?.dismiss(animated: true, completion: nil)
        }
        present(cameraViewController, animated: true, completion: nil)
    }


    func saveImage() -> Promise<Void> {
        var promiseArr: [Promise<String>] = []
        if userCard.idCardUrl == "", let img = IDCardImageView.image {
            promiseArr.append(uploadImg(UIImageJPEGRepresentation(img, 0.2)!, key: "idcard"))
        }
        if userCard.workinfoCardUrl == "", let img = workingIDCardImageView.image {
            promiseArr.append(uploadImg(UIImageJPEGRepresentation(img, 0.2)!, key: "workingidcard"))
        }
        return when(fulfilled: promiseArr).then { [weak self] stringArr -> Promise<Void> in
            let _ = stringArr.map { url -> Void in
                if url.hasSuffix("_idcard.jpg") {
                    self?.userCard.idCardUrl = url
                }
                if url.hasSuffix("_workingidcard.jpg") {
                    self?.userCard.workinfoCardUrl = url
                }
            }
            return Promise(value: ())
        }
    }

    func uploadImg(_ data: Data, key: String) -> Promise<String> {
        let (wrappingPromise, fulfill, reject) = Promise<String>.pending()
        let put = OSSPutObjectRequest()
        put.bucketName = aliyunBucket
        put.objectKey = "\(appUser.userId!)_\(key).jpg"
        put.uploadingData = data
        let putTask = client.putObject(put)
        putTask.continue({ (task: OSSTask) -> Any? in
            if task.error == nil {
                let url = "https://\(aliyunBucket).\(aliyunEndpoint).com/\(put.objectKey)"
                fulfill(url)
            } else {
                dPrint(task.error!)
                reject(task.error!)
            }
            return nil
        }, cancellationToken: nil)
        return wrappingPromise
    }
}
